package com.yhw.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yhw.common.exception.Assert;
import com.yhw.common.result.ResponseEnum;
import com.yhw.srb.base.dto.SmsDTO;
import com.yhw.srb.core.enums.TransTypeEnum;
import com.yhw.srb.core.hfb.FormHelper;
import com.yhw.srb.core.hfb.HfbConst;
import com.yhw.srb.core.hfb.RequestHelper;
import com.yhw.srb.core.mapper.UserInfoMapper;
import com.yhw.srb.core.pojo.bo.TransFlowBO;
import com.yhw.srb.core.pojo.entity.UserAccount;
import com.yhw.srb.core.mapper.UserAccountMapper;
import com.yhw.srb.core.pojo.entity.UserInfo;
import com.yhw.srb.core.service.TransFlowService;
import com.yhw.srb.core.service.UserAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhw.srb.core.service.UserBindService;
import com.yhw.srb.core.service.UserInfoService;
import com.yhw.srb.core.util.LendNoUtils;
import com.yhw.srb.rabbitmq.constant.MQConst;
import com.yhw.srb.rabbitmq.service.MQService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author yhw
 * @since 2022-08-29
 */
@Service
@Slf4j
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private TransFlowService transFlowService;

    @Resource
    private UserBindService userBindService;

    @Resource
    private UserAccountService userAccountService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private MQService mqService;

    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);
        String bindCode = userInfo.getBindCode();
        //判断账户绑定状态
        Assert.notEmpty(bindCode, ResponseEnum.USER_NO_BIND_ERROR);  // USER_NO_BIND_ERROR(302, "用户未绑定")

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentBillNo", LendNoUtils.getChargeNo());
        paramMap.put("bindCode", bindCode);
        paramMap.put("chargeAmt", chargeAmt);
        paramMap.put("feeAmt", new BigDecimal("0"));
        paramMap.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL); //检查常量是否正确
        paramMap.put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);

        //构建充值自动提交表单
        String formStr = FormHelper.buildForm(HfbConst.RECHARGE_URL, paramMap);

        return formStr;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String notify(Map<String, Object> paramMap) {

        /*
            因为hfb 没有收到 sucess 就会 一直请求(5次)
            如果 在 srb 返回 sucess 的时候 出现网络异常网络错误 导致hfb就没有接收到 那它就会再次请求 那srb就会再次更新用户账户(余额变更多)
            所以我们要 保证 接口的幂等性
            1. 设置唯一索引 （数据库表 流水号列 设置唯一索引unique，即使回调重复执行，遇到唯一索引，就会抛出异常，从而使事务回滚。）
            2. 判断流水是否存在  (如果存在，则从业务方法中直接退出)
         */
        //判断交易流水是否存在
        String agentBillNo = (String)paramMap.get("agentBillNo"); //商户充值订单号  流水号
        boolean isSave = transFlowService.isSaveTransFlow(agentBillNo);
        if(isSave){
            log.warn("幂等性返回");
            return "success";
        }

        String bindCode = (String)paramMap.get("bindCode"); // 充值人绑定协议号
        String chargeAmt = (String)paramMap.get("chargeAmt"); // 充值金额

        // 更新用户账户
        // 绑定的时候 useraccount就存在了 所以这里应该是update 而不是insert
        baseMapper.updateAccount(bindCode,new BigDecimal(chargeAmt),new BigDecimal(0));


        //增加交易流水
        TransFlowBO transFlowBO = new TransFlowBO(agentBillNo, bindCode, new BigDecimal(chargeAmt), TransTypeEnum.RECHARGE, "这是备注");
        transFlowService.saveTransFlow(transFlowBO);

        // Rabbit MQ应用
        //发消息
        log.info("发消息");
        String mobile = userInfoService.getMobileByBindCode(bindCode);
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setMobile(mobile);
        smsDTO.setMessage("充值成功");
        mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS,MQConst.ROUTING_SMS_ITEM,smsDTO);

        return "success";
    }

    @Override
    public BigDecimal getAccount(Long userId) {

        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccount::getUserId,userId);
        UserAccount userAccount = baseMapper.selectOne(queryWrapper);
        return userAccount.getAmount();
    }

    @Override
    public String commitWithdraw(BigDecimal fetchAmt, Long userId) {

        //账户可用余额充足：当前用户的余额 >= 当前用户的提现金额
        BigDecimal amount = userAccountService.getAccount(userId);
        Assert.isTrue(amount.doubleValue() >= fetchAmt.doubleValue(),
                ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);   //  NOT_SUFFICIENT_FUNDS_ERROR(307, "余额不足"),

        String bindCode = userBindService.getBindCodeByUserId(userId);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentBillNo", LendNoUtils.getWithdrawNo());
        paramMap.put("bindCode", bindCode);
        paramMap.put("fetchAmt", fetchAmt);
        paramMap.put("feeAmt", new BigDecimal(0));
        paramMap.put("notifyUrl", HfbConst.WITHDRAW_NOTIFY_URL);
        paramMap.put("returnUrl", HfbConst.WITHDRAW_RETURN_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        String sign = RequestHelper.getSign(paramMap);
        paramMap.put("sign", sign);

        //构建 自动 提交 字符串表单
        String formStr = FormHelper.buildForm(HfbConst.WITHDRAW_URL, paramMap);
        return formStr;
    }

    @Override
    public void notifyWithdraw(Map<String, Object> paramMap) {

        // 接口幂等性
        String agentBillNo = (String) paramMap.get("agentBillNo");
        boolean result = transFlowService.isSaveTransFlow(agentBillNo);
        if (result){
            log.warn("幂等性返回");
            return;
        }

        String bindCode = (String)paramMap.get("bindCode");
        String fetchAmt = (String)paramMap.get("fetchAmt");

        // 更新用户账户
        baseMapper.updateAccount(bindCode,new BigDecimal("-"+fetchAmt),new BigDecimal(0));

        // 增加交易流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(fetchAmt),
                TransTypeEnum.WITHDRAW,
                "提现");
        transFlowService.saveTransFlow(transFlowBO);
    }
}
